package top.ssrsdev.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;

/**
 * 代码生成工具类
 *
 * @author ssrs
 */
@SuppressWarnings("ALL" )
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EightRoesGenerator {
    /**
     * 数据库链接
     */
    private String jdbcUrl;
    /**
     * 用户名
     */
    private String userName;
    /**
     * 密码
     */
    private String password;
    /**
     * 数据库驱动
     */
    private String driver;
    /**
     * 作者
     */
    private String author;
    /**
     * 项目路径
     */
    private String projectPath;
    /**
     * 父包路径
     */
    private String packageParent;
    /**
     * 模块名称
     */
    private String moduleName;

    /**
     * 表前缀
     */
    private String tablePrefix;


    public void generate(String... tableNamesInclude) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        // 输出目录
        gc.setOutputDir(projectPath + "/src/main/java" );
        // 是否覆盖文件
        gc.setFileOverride(true);
        // 开启 activeRecord 模式
        gc.setActiveRecord(false);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(false);
        // XML column list
        gc.setBaseColumnList(false);
        //是否生成 kotlin 代码
        gc.setKotlin(false);
        // 作者
        gc.setAuthor(author);
        // 实体属性 Swagger2 注解
        // gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbcUrl);
        dsc.setDriverName(driver);
        dsc.setUsername(userName);
        dsc.setPassword(password);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {

                if (fieldType.toLowerCase().contains("bit" )) {
                    return DbColumnType.BOOLEAN;
                }
                if (fieldType.toLowerCase().contains("tinyint" )) {
                    return DbColumnType.BOOLEAN;
                }
                if (fieldType.toLowerCase().contains("datetime" )) {
                    return DbColumnType.LOCAL_DATE_TIME;
                }
                if (fieldType.toLowerCase().contains("date" )) {
                    return DbColumnType.LOCAL_DATE;
                }
                if (fieldType.toLowerCase().contains("time" )) {
                    return DbColumnType.LOCAL_TIME;
                }
                return super.processTypeConvert(globalConfig, fieldType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        // 设置模块名，会在指定parent包下生成一个指定的模块包
        pc.setModuleName(moduleName);
        pc.setParent(packageParent);
        pc.setEntity("model.entity" );
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                Arrays.asList(tableNamesInclude).forEach(item -> {
                    Map params = Objects.isNull(this.getMap()) ? new HashMap() : this.getMap();
                    this.setMap(params);
                });
            }
        };

        // 如果模板引擎是 freemarker
        // String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        // 调整xml生成目录
        focList.add(new FileOutConfig("/templates/mapper.xml.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        // 生成自定义模板
        focList.add(new FileOutConfig("/templates/addDTO.java.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String path = packageParent.replaceAll("\\." , "/" ) + "/" + moduleName.replaceAll("\\." , "/" );
                return projectPath + "/src/main/java/" + path + "/model/dto/" + tableInfo.getEntityName() + "AddDTO" + StringPool.DOT_JAVA;
            }
        });
        // 生成自定义模板
        focList.add(new FileOutConfig("/templates/editDTO.java.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String path = packageParent.replaceAll("\\." , "/" ) + "/" + moduleName.replaceAll("\\." , "/" );
                return projectPath + "/src/main/java/" + path + "/model/dto/" + tableInfo.getEntityName() + "EditDTO" + StringPool.DOT_JAVA;
            }
        });
        // 生成自定义模板
        focList.add(new FileOutConfig("/templates/queryDTO.java.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String path = packageParent.replaceAll("\\." , "/" ) + "/" + moduleName.replaceAll("\\." , "/" );
                return projectPath + "/src/main/java/" + path + "/model/dto/" + tableInfo.getEntityName() + "QueryDTO" + StringPool.DOT_JAVA;
            }
        });
        // 生成自定义模板，VUE
        focList.add(new FileOutConfig("/templates/vue/api.ts.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/vue/" + tableInfo.getEntityPath() + "/" + tableInfo.getEntityPath() + ".ts";
            }
        });
        // 生成自定义模板，VUE
        focList.add(new FileOutConfig("/templates/vue/data.ts.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/vue/" + tableInfo.getEntityPath() + "/" + "data.ts";
            }
        });
        // 生成自定义模板，VUE
        focList.add(new FileOutConfig("/templates/vue/FormModal.vue.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/vue/" + tableInfo.getEntityPath() + "/" + "FormModal.vue";
            }
        });
        // 生成自定义模板，VUE
        focList.add(new FileOutConfig("/templates/vue/index.vue.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/vue/" + tableInfo.getEntityPath() + "/" + "index.vue";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null)
                .setEntity("/templates/entity.java.vm" )
                .setMapper("/templates/mapper.java.vm" )
                .setController("/templates/controller.java.vm" )
                .setService("/templates/service.java.vm" )
                .setServiceImpl("/templates/serviceImpl.java.vm" );
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(tablePrefix);// 去除前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(tableNamesInclude);
        strategy.setChainModel(true);
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("create_user" , FieldFill.INSERT));
        tableFillList.add(new TableFill("create_time" , FieldFill.INSERT));
        tableFillList.add(new TableFill("update_user" , FieldFill.UPDATE));
        tableFillList.add(new TableFill("update_time" , FieldFill.UPDATE));
        strategy.setTableFillList(tableFillList);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
        System.out.println(mpg.getTemplateEngine().getObjectMap(new TableInfo()));
    }

    public static void main(String[] args) {
        EightRoesGenerator eightRoesGenerator = new EightRoesGenerator().builder()
                .jdbcUrl("jdbc:mysql://127.0.0.1:3306/eight-roes-dev?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false" )
                .userName("root" )
                .password("123456" )
                .driver("com.mysql.cj.jdbc.Driver" )
                .author("author" )
                .projectPath("D:\\tempCode" )
                .packageParent("com.ssrs" )
                .tablePrefix("sys_")
                .moduleName("platform" ).build();

        eightRoesGenerator.generate("sys_code");
    }


}
